//项目亮点=>像nuxt一样可以自动进行配置
//项目难点=>扁平路由转换成树形
//require.context('路径',"是否递归引入",'正则') 一次导入多个模块

let files = require.context("@/pages", true, /\.vue$/);
// console.log(files.keys());
//创建路由配置
let repeatRoutes = files.keys().map((path) => {
  let currentComponent = files(path).default;
  //解构组件export default导出的对象中添加的属性
  let { meta, name, redirect } = currentComponent;
  //通过正则，去掉index.vue或去掉.vue的后缀
  let regExp = /(\/index\.vue|\.vue)$/;
  path = path.substring(1).replace(regExp, "");
  //   console.log(path);

  return {
    path: path ? path : "/pages",
    //重定向、name、meta路由元信息
    meta: meta ?? {},
    name: name ?? path.substring(1).split("/").join("-").toLowerCase(),
    redirect: redirect ?? null,
    component: () => import("@/pages" + path),
  };
});
// console.log(repeatRoutes);

function convertTree(repeatRoutes) {
  repeatRoutes = [...repeatRoutes]; //浅拷贝，不改变输入值
  let treeRoutes = [];
  //先给数据添加id和pid
  repeatRoutes.forEach((route) => {
    let routePathArr = route.path.substring(1).split("/");
    // console.log(routePathArr);
    //length为1的都是根节点
    //需要添加id和pid

    //正常添加id
    route.id = routePathArr.join("-");
    if (routePathArr.length > 1) {
      //浅拷贝routePathArr；
      let pathArr = [...routePathArr];
      pathArr.pop();
      // console.log(pathArr);
      let pid = pathArr.join("-");
      // console.log(pid);
      route.pid = pid;
    }
  });
  // console.log(repeatRoutes);
  //扁平数据转树形
  repeatRoutes.forEach((route) => {
    //将多有的路径都变成小写
    route.path = route.path.toLowerCase();
    //单独对page404进行额外处理
    if (route.path == "/page404") {
      route.path = "*";
    }
    //查找是否存在父节点
    let parent = repeatRoutes.find((v) => route.pid === v.id);
    if (parent) {
      if (!parent.children) {
        parent.children = [];
      }
      route.path = route.path.substring(1).split("/").pop();
      // console.log(route.path);
      parent.children.push(route);
    } else {
      treeRoutes.push(route);
    }
  });
  return treeRoutes;
}
let res = convertTree(repeatRoutes);
console.log(res);
export default [...res];
